package com.ml.mall.service.product.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ml.mall.bean.page.Page;
import com.ml.mall.bean.req.BaseBeanReq;
import com.ml.mall.bean.req.product.*;
import com.ml.mall.bean.req.product.vo.ProductPicEditVO;
import com.ml.mall.bean.req.product.vo.ProductPicNewVO;
import com.ml.mall.bean.res.product.SysProductQueryOneRes;
import com.ml.mall.bean.res.product.SysProductQueryPageRes;
import com.ml.mall.bean.res.product.SysProductQueryTreeRes;
import com.ml.mall.bean.res.product.SysProductShopPageRes;
import com.ml.mall.bean.vo.variant.SysProductVariantSalesVo;
import com.ml.mall.consts.CommonConsts;
import com.ml.mall.consts.UserRoleTypeConsts;
import com.ml.mall.entity.category.SysACategory;
import com.ml.mall.entity.company.SysCompany;
import com.ml.mall.entity.deduct.SysADeduct;
import com.ml.mall.entity.product.SysProduct;
import com.ml.mall.entity.product.SysProductPic;
import com.ml.mall.entity.sys.SysUser;
import com.ml.mall.entity.tax.Tax;
import com.ml.mall.entity.variant.SysProductVariant;
import com.ml.mall.entity.variant.SysProductVariantPic;
import com.ml.mall.entity.variant.SysProductVariantSku;
import com.ml.mall.enums.CommonEnum;
import com.ml.mall.enums.SysSeqNameEnum;
import com.ml.mall.exception.BizException;
import com.ml.mall.mapper.product.SysProductMapper;
import com.ml.mall.mapper.product.SysProductPicMapper;
import com.ml.mall.mapper.variant.SysProductVariantMapper;
import com.ml.mall.security.JwtUtil;
import com.ml.mall.service.asyn.ProductMailServiceImplAsyn;
import com.ml.mall.service.category.SysACategoryService;
import com.ml.mall.service.common.CommonSeqService;
import com.ml.mall.service.company.SysCompanyService;
import com.ml.mall.service.deduct.SysADeductService;
import com.ml.mall.service.product.SysProductPicService;
import com.ml.mall.service.product.SysProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ml.mall.service.tax.TaxService;
import com.ml.mall.service.variant.SysProductVariantPicService;
import com.ml.mall.service.variant.SysProductVariantService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* <p>
    *  服务实现类
    * </p>
*
* @author kyyang
* Created 2021-05-15
*/
@Service
@Slf4j
public class SysProductServiceImpl extends ServiceImpl<SysProductMapper, SysProduct> implements SysProductService {

    @Autowired
    private  SysProductMapper  sysProductMapper;

    @Autowired
    private CommonSeqService commonSeqService;

    @Autowired
    private SysProductVariantPicService sysProductVariantPicService;

    @Autowired
    private SysProductVariantService sysProductVariantService;

    @Autowired
    private SysACategoryService sysACategoryService;

    @Autowired
    private SysCompanyService sysCompanyService;

    @Lazy
    @Autowired
    private SysProductVariantMapper sysProductVariantMapper;

    @Autowired
    private TaxService taxService;

    @Autowired
    private SysADeductService sysADeductService;

    @Autowired
    private SysProductPicService sysProductPicService;

    @Lazy
    @Autowired
    private ProductMailServiceImplAsyn productMailServiceImplAsyn;

    @Override
    @Transactional
    public Long sysProductNew(SysProductNewReq sysProductNewReq) {
        Long pid = commonSeqService.nextSysOrderSeq(SysSeqNameEnum.SEQ_PROD_GENERATE.getCode(),6);
        SysProduct sysProduct = new SysProduct();
        BeanUtils.copyProperties(sysProductNewReq,sysProduct);
        sysProduct.setState(0); //默认无效
        sysProduct.setProductId(pid);
        int insert = sysProductMapper.insert(sysProduct);
        //存储产品图片
        List<ProductPicNewVO> picArr = sysProductNewReq.getPicArr();
        if(picArr!=null&&picArr.size()>0){
            List<SysProductPic> list = new ArrayList<>();
            for(ProductPicNewVO p:picArr){
                SysProductPic sysProductPic = new SysProductPic();
                sysProductPic.setProductId(pid);
                sysProductPic.setIndex(p.getIndex());
                sysProductPic.setPicUrl(p.getPicUrl());
                list.add(sysProductPic);
            }
            if(list.size()>0){
                log.info("list===={}",list);
                sysProductPicService.saveBatch(list);
            }
        }

        //异步发送邮件
        productMailServiceImplAsyn.sysProductNewMailAsyn(sysProductNewReq);
        return pid;
    }

    @Override
    @Transactional
    public int sysProductEdit(SysProductEditReq sysProductEditReq) {
        SysUser currentUser = JwtUtil.getCurrentUser();
        //复制前端传过来的值
        SysProduct sysProduct = new SysProduct();
        BeanUtils.copyProperties(sysProductEditReq, sysProduct);
        log.info("sysProduct===={}",sysProduct);
        //产品状态更改逻辑 状态0 3只有管理员可以修改 0 1 2 3
        int i= changeProductState(sysProduct,currentUser,sysProductEditReq);
        //删除产品关联的所有图片并且添加最新的图片
        removoAndInsertPic(sysProductEditReq.getProductId(),sysProductEditReq.getPicArr());
        //更新产品下变体的目录
        if(null != sysProductEditReq.getCategoryId() && !"".equals(sysProductEditReq.getCategoryId())){
            changeVariantStateCategory(sysProductEditReq.getCategoryId(),sysProductEditReq.getProductId());
        }
        //更新产品下变体的状态
        changeVariantState(sysProduct.getState().intValue(),sysProductEditReq.getProductId());
        return i;
    }

    private void changeVariantStateCategory(String categoryId, Long productId) {
        UpdateWrapper<SysProductVariant> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("product_id",productId);
        updateWrapper.eq("expiry_dt",new Date(CommonConsts.MAX_EXPIRY_TIME));
        updateWrapper.set("category_id",categoryId);
        sysProductVariantService.update(updateWrapper);
    }

    private void changeVariantState(int productState, Long productId) {
        int state=0;
        if(productState != 3){
            state=productState;
        }
        UpdateWrapper<SysProductVariant> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("product_id",productId);
        updateWrapper.set("state",state);
        sysProductVariantService.update(updateWrapper);

    }

    private int changeProductState(SysProduct sysProduct, SysUser currentUser,SysProductEditReq sysProductEditReq) {
        //产品原数据
        SysProduct sysProduct1 = sysProductMapper.selectById(sysProductEditReq.getId());
        if(null == sysProduct1){
            throw new BizException(CommonEnum.SELECT_ERROR);
        }
        int productState = sysProduct.getState().intValue();
        if(UserRoleTypeConsts.ROLE_TYPE_1 != currentUser.getRoleType().intValue()){
            //把待定变为其他状态只有管理员才能更改
            if(sysProductEditReq.getState() == 0 && productState != sysProductEditReq.getState()){
                throw new BizException(CommonEnum.UPDATE_PRODUCT_STATE_ERROR);
            }
            if(sysProductEditReq.getState() == 3 && productState != sysProductEditReq.getState()){
                throw new BizException(CommonEnum.UPDATE_PRODUCT_STATE_ERROR);
            }
        }
        //如果产品通过了拒绝原因设为null
        if(sysProduct.getState() != 3 && !sysProduct.getState().equals("2")){
            sysProduct.setRefusReasion(null);
        }
        int i = sysProductMapper.updateById(sysProduct);
        return i;
    }

    private void removoAndInsertPic(Long productId, List<ProductPicEditVO> picArr) {
        QueryWrapper<SysProductPic> wrapper =  new QueryWrapper<>();
        wrapper.eq("product_id",productId);
        sysProductPicService.remove(wrapper);
        if (picArr != null && picArr.size() > 0) {
            List<SysProductPic> addlist = new ArrayList<>();
            for (ProductPicEditVO p : picArr) {
                SysProductPic sysProductPic = new SysProductPic();
                sysProductPic.setIndex(p.getIndex());
                sysProductPic.setPicUrl(p.getPicUrl());
                sysProductPic.setProductId(productId);
                addlist.add(sysProductPic);
                log.info("addlist===={}",addlist);
            }
            if(addlist.size()>0){
                sysProductPicService.saveBatch(addlist);
            }
        }
    }

    @Override
    @Transactional
    public String sysProductDel(List<Long> ids) {
        StringBuilder sb = new StringBuilder();
        for(Long id:ids){
            SysProduct sysProduct = sysProductMapper.selectById(id);
            if(sysProduct==null){
                sb.append("当前产品不存在："+id+" ");
                continue;
            }
            Long productId = sysProduct.getProductId();
            QueryWrapper<SysProductVariant> wrapper =  new QueryWrapper<>();
            wrapper.eq("product_id",productId);
            List<SysProductVariant> list = sysProductVariantService.list(wrapper);
            if(list!=null&&list.size()>0){
                sb.append("当前  "+sysProduct.getProductName()+" 存在实体产品不能删除！");
                continue;
            }
            QueryWrapper<SysProductPic> wrapper2 =  new QueryWrapper<>();
            wrapper2.eq("product_id",productId);
            sysProductPicService.remove(wrapper2);
            sysProductMapper.deleteById(id);
        }
        return sb.toString();
    }

    @Override
    public SysProductQueryOneRes sysProductByOne(BaseBeanReq baseBeanReq) {
        SysProductQueryOneRes sysProductQueryOneRes = new SysProductQueryOneRes();
        SysProduct sysProduct = sysProductMapper.selectById(baseBeanReq.getId());
        BeanUtils.copyProperties(sysProduct, sysProductQueryOneRes);
        //图片信息
        QueryWrapper<SysProductPic> wrapper2 =  new QueryWrapper<>();
        wrapper2.eq("product_id",sysProduct.getProductId());
        wrapper2.orderByAsc("`index`");
        List<SysProductPic> list = sysProductPicService.list(wrapper2);
        if(list!=null&&list.size()>0){
            String listToJsonString = JSONObject.toJSONString(list);
            List<ProductPicEditVO> picArr = JSON.parseArray(listToJsonString, ProductPicEditVO.class);
            sysProductQueryOneRes.setPicArr(picArr);
        }
        //分类名称
        QueryWrapper<SysACategory> wrapper3 =  new QueryWrapper<>();
        wrapper3.eq("category_id",sysProduct.getCategoryId());
        SysACategory one = sysACategoryService.getOne(wrapper3);
        if(one!=null){
            sysProductQueryOneRes.setCategoryName(one.getCategoryName());
            sysProductQueryOneRes.setTreeName(one.getTreeName());
        }
        //公司名称
        QueryWrapper<SysCompany> wrapper4 =  new QueryWrapper<>();
        wrapper4.eq("company_id",sysProduct.getSupplierId());
        SysCompany one2 = sysCompanyService.getOne(wrapper4);
        if(one2!=null){
            sysProductQueryOneRes.setSuplierName(one2.getCompanyName());
        }
        return sysProductQueryOneRes;
    }

    @Override
    public Page<SysProductQueryPageRes> sysProductByPage(SysProductQueryPageReq req) {
        Page<SysProductQueryPageRes> result = new Page<>(req.getPageIndex(),req.getPageNum());
        //查询数量
        QueryWrapper<SysProduct> wrapper = new QueryWrapper<>();
        SysUser currentUser = JwtUtil.getCurrentUser();
        if(req.getSupplierId()!=null){
            wrapper.eq("supplier_id",req.getSupplierId());
        }
        if(req.getCategoryId()!=null){
            wrapper.eq("category_id",req.getCategoryId());
        }
        if(req.getProductName()!=null){
            wrapper.like("product_name",req.getProductName());
        }
        log.info("req===={}",req);
        if(currentUser.getRoleType() != CommonConsts.ROLE_TYPE_ADMIN) {
            wrapper.eq("supplier_id", currentUser.getCompanyId());
            req.setSupplierId(currentUser.getCompanyId());
        }
        if(req.getState()!=null){
            wrapper.eq("state",req.getState());
        }
        log.info("req===={}",req);
        Integer count = sysProductMapper.selectCount(wrapper);
        //函数与 order by 联合使用 报错
        wrapper.orderByDesc("id");
        if(count>0){
            List<SysProductQueryPageRes> list = sysProductMapper.selectSysProductByPage(req);
            result.setRecords(list);
            result.setTotal(count);
        }
        return result;
    }

    @Override
    public List<SysProductQueryTreeRes> sysProductQueryTree(SysProductQueryTreeReq sysProductQueryTreeReq) {
        List<SysProductQueryTreeRes>  sysProductQueryTreeRess = sysProductVariantMapper.sysProductQueryTree(sysProductQueryTreeReq.getProductId());
        if(sysProductQueryTreeRess!=null&&sysProductQueryTreeRess.size()>0){
//            //查询税收
//            QueryWrapper<Tax> wrapper = new QueryWrapper<>();
//            wrapper.eq("state",0);
//            Tax one = taxService.getOne(wrapper);
//            BigDecimal taxRate = BigDecimal.ZERO;
//
//            //查询系统抽取
//            List<SysADeduct> list = sysADeductService.list();
//            BigDecimal deduct = BigDecimal.ZERO;
//
//            for(SysProductQueryTreeRes sysProductQueryTreeRes :sysProductQueryTreeRess){
//
//                //查询售价
//                BigDecimal price = sysProductQueryTreeRes.getPrice();
//
//                if(one!=null&&sysProductQueryTreeRes.getIncludTax()==1){
//                    taxRate = price.multiply(one.getTaxRate());
//                }
//                if(list!=null&&list.size()>0){
//                    SysADeduct sysADeduct = list.get(0);
//                    BigDecimal deductRate = sysADeduct.getDeductRate();
//                    deduct = price.multiply(deductRate);
//                }
//                price = price.add(taxRate).add(deduct);
//                sysProductQueryTreeRes.setPrice(price);
//            }
            return sysProductQueryTreeRess;
        }
        sysProductQueryTreeRess = new ArrayList<>();
        return sysProductQueryTreeRess;
    }

    @Override
    public Page<SysProductShopPageRes> sysProductQueryShopPage(SysProductShopPageReq sysProductShopPageReq) {
        //产品查询单独接口：方便目录like筛选；product like筛选；随机查询ORDER BY RAND()
        //商店搜索的时候按目录 是 like 'category_id%'
        //目录有多级 比如有5级 每一级有产品 根目录要搜索到 子目录的产品
        //categoryid 的规则是 拼接上级目录id
        //比如一级是1001  二级1001123 三级 100112345 四级 10011234511 ...

        //首先对sys_product_variant进行分页查询
        IPage<SysProductVariant> productVariantPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>
                (sysProductShopPageReq.getPageNum(),sysProductShopPageReq.getPageIndex());
        QueryWrapper<SysProductVariant> selectProductVariantWrapper = new QueryWrapper<>();
        selectProductVariantWrapper.likeLeft("category_id",sysProductShopPageReq.getCategoryId());
        productVariantPage = sysProductVariantMapper.selectPage(productVariantPage, selectProductVariantWrapper);
//        sysProductMapper.selectShopOfProductByPage(sysProductShopPageReq.get)



        List<SysProductShopPageRes> resList = new ArrayList<>();
        for(SysProductVariant sysProductVariant:productVariantPage.getRecords()){
            SysProductShopPageRes productShopPageRes = new SysProductShopPageRes();
            BeanUtil.copyProperties(sysProductVariant,productShopPageRes);
            productShopPageRes.setPicUrl(sysProductMapper.selectPicUrlForProductShopPage(productShopPageRes.getProductId()));
//            productShopPageRes.setBrand(sysProductMapper.selectBrandForProductShopPage(productShopPageRes.getProductId()));
            //查询是否有限时优惠信息
//             sysProductMapper.selectCouponMessage(productShopPageRes.getVariantId());

            resList.add(productShopPageRes);
        }


        return null;
    }

    @Override
    public SysProduct selectByProductId(Long productId) {
        QueryWrapper<SysProduct> w1 = new QueryWrapper<>();
        w1.eq("product_id",productId);
        SysProduct sysProduct = sysProductMapper.selectOne(w1);
        return sysProduct;
    }
}
